#ifndef TRANSFORMERCONTENTPORTSTATEPROTOCOL_HPP_3
#define TRANSFORMERCONTENTPORTSTATEPROTOCOL_HPP_3

#include <stdio.h>
#include <stdlib.h>

/////////////////////////////////////////////////////////////
/// port heartbeat and closeing protocol
///		used to async the local and the stack port, any port exist in stack but not local, remvoe it
///
/// content format:
///
/// name   |  length  |  mainCode | subCode | port |
/// length |    2     |    1      |   1     |  4   |
/// offest |    0     |    2      |   3     |  4   |
///////////////////////////////////////////////////////////////
class transContentPortStateProtocol{
	public:
		static void setPacketLength(char* buffer, int length){
			*((short*)(buffer)) = (short)length;
		}

		static int getPacketLength(const char* buffer){
			return *((short*)(buffer));
		}

		static void setPacketMainMessageCode(char* buffer, int code){
			buffer[2] = (char)code;
		}

		static int getPacketMainMessageCode(const char* buffer, int towards){
			return towards==DUMP_PROTOCOL_PACKET_IN ? buffer[0]:buffer[2];
		}

		static void setPacketSubMessageCode(char* buffer, int code){
			buffer[3] = (char)code;
		}

		static int getPacketSubMessageCode(const char* buffer, int towards){
			return towards==DUMP_PROTOCOL_PACKET_IN ? buffer[1]:buffer[3];
		}

		static void setPacketPort(char* buffer, int port){
			*((int*)(buffer+4)) = port;
		}

		static int getPacketPort(const char* buffer, int towards){
			return towards==DUMP_PROTOCOL_PACKET_IN  ? *((int*)(buffer+2)) : *((int*)(buffer+4));
		}

		static void dumpPacket(const char* buffer, int towards, const char* fileName){
			FILE* dumpFile = fopen(fileName, "w+");
			char timer[256]={0};
			if(dumpFile == NULL){
				return;
			}
			TransContentSetting::getTimeStr(timer, 256);
			fprintf(dumpFile, "\t\t\t\tdump port state protocol\n");
			fprintf(dumpFile, "\ttime stamp: %s\n", timer);
			if(towards==DUMP_PROTOCOL_PACKET_OUT)
				fprintf(dumpFile, "\tpacket length is: %d\n", getPacketLength(buffer));
			fprintf(dumpFile, "\tMain Message Code: %d\n", getPacketMainMessageCode(buffer, towards));
			fprintf(dumpFile, "\tSub Message Code: %d\n", getPacketSubMessageCode(buffer, towards));
			fprintf(dumpFile, "\t port is: %d\n", getPacketPort(buffer, towards));
		}
};
#endif //TRANSFORMERCONTENTPORTSTATEPROTOCOL_HPP_3
